<!doctype html>
<html><head>
<script type="text/javascript">

const serverPort = {{{:port}}};
var csocket = {};

const jul_uri = 'ws://localhost:' + serverPort
var jsocket = new WebSocket(jul_uri);
console.log('listening on : ' +  jul_uri);


// Make the function wait until the connection is ready
function waitForSocketConnection(socket, callback){
  setTimeout(
      function () {
          if (socket.readyState === 1) {
              if(callback != null){
                  callback();
              }
              return;
          } else {
              waitForSocketConnection(socket, callback);
          }

      }, 100); // wait 100 milisecond
}


// send & receive callbacks
jsocket.onopen = function() {
  jsocket.onmessage = function(response) {
    var msg = JSON.parse(response.data);
    console.log("jsocket msg : ")
    console.log(msg);

    switch(msg.command) {
      case 'connect':
        var nsocket = new WebSocket(msg.uri);

        csocket[msg.uri] = nsocket;

        nsocket.onopen = function() {
          nsocket.onmessage = function(response) {
            var msg2 = JSON.parse(response.data);
            msg2["origin"] = msg.uri;
            console.log("nsocket msg : ")
            console.log(msg2);

            jsocket.send(JSON.stringify(msg2));
          };
        };

        nsocket.onerror= msg => console.log("nsocket error: " + msg);
        nsocket.onclose= () => console.log("nsocket closing");

        break;

      case 'send':
        if (typeof csocket[msg.session] !== 'undefined') {
          console.log('forwarding to chromium')

          var ws = csocket[msg.session]
          var msg2 = JSON.stringify(msg.payload)
          waitForSocketConnection(ws, () => ws.send(msg2) )
          // csocket[msg.session].send(JSON.stringify(msg.payload))
        } else {
          console.log('wsocket to this session not yet defined')
        }
        break;

      default:
        break;
    }

  };
}

jsocket.onerror= function(msg) {
  console.log("jsocket error: ");
  console.log(msg);
}

jsocket.onclose= function() {
  console.log("jsocket closing");
}

</script>
</head>
